package com.yundashi.updateapputils.update

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import com.yundashi.updateapputils.extension.*
import com.yundashi.updateapputils.ui.UpdateAppActivity
import com.yundashi.updateapputils.util.AppUtil
import com.yundashi.updateapputils.util.YXServiceManager
import com.zcapi

/**
 * desc: UpdateAppReceiver
 * author: teprinciple on 2019/06/3.
 */
internal class UpdateAppReceiver : BroadcastReceiver() {

    private val notificationChannel = "1001"

    private val updateConfig by lazy { UpdateAppUtils.updateInfo.config }

    private val uiConfig by lazy { UpdateAppUtils.updateInfo.uiConfig }

    private var lastProgress = 0

    override fun onReceive(context: Context, intent: Intent) {

        when (intent.action) {

            // 下载中
            context.packageName + ACTION_UPDATE -> {
                // 进度
                val progress = intent.getIntExtra(KEY_OF_INTENT_PROGRESS, 0)

                val nm =
                    context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

                (progress != -1000).yes {
                    lastProgress = progress
                }

                // 显示通知栏
                val notifyId = 1
                updateConfig.isShowNotification.yes {
                    showNotification(context, notifyId, progress, notificationChannel, nm)
                }

                // 下载完成
                if (progress == 100) {
                    if (updateConfig.isApk) {
                        handleDownloadComplete(context, notifyId, nm)
                    }
                }
            }

            // 重新下载
            context.packageName + ACTION_RE_DOWNLOAD -> {
                DownloadAppUtils.reDownload()
            }
        }
    }

    /**
     * 下载完成后的逻辑
     */
    private fun handleDownloadComplete(context: Context, notifyId: Int, nm: NotificationManager?) {
        // 关闭通知栏
        nm?.let {
            nm.cancel(notifyId)
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                nm.deleteNotificationChannel(notificationChannel)
            }
        }

        val checkPackInfo =
            AppUtil.instance.checkPackInfo(updateConfig.packageName, context)
        if (checkPackInfo) { // 存在
            val versionCode = AppUtil.instance.getVersionCode(context, updateConfig.packageName)
            val apkType =
                if (AppUtil.instance.isApkDebugable(context, updateConfig.packageName)) 1 else 2
            log("apkType：${apkType} updateConfig.newApkType：${updateConfig.newApkType}")
            log("versionCode：${versionCode} updateConfig.newVersionCode：${updateConfig.newVersionCode}")
            if (apkType == updateConfig.newApkType) {
                if (versionCode < updateConfig.newVersionCode) {
                    log("正常覆盖安装")
                    installApk(context)
                } else if (versionCode > updateConfig.newVersionCode) {
                    log("新apk版本较低 卸载安装")
                    unInstallApk(context, updateConfig.packageName)
                } else if (versionCode == updateConfig.newVersionCode) {
                    log("无操作")
                    UpdateAppActivity.activity?.finish()
                }
            } else {
                log("apk类型不一致，卸载安装")
                unInstallApk(context, updateConfig.packageName)
            }
        } else {
            log("此apk未安装")
            installApk(context)
        }

    }

    /**
     * 静默卸载
     * */
    private fun unInstallApk(context: Context, packageName: String) {
        if (packageName.isNullOrEmpty()) return
        log("UpdateAppReceiver-unInstallApk===${packageName}")

        //卸载模式（0默认卸载 2俊鹏广播卸载 3印象service卸载）
        when (updateConfig.installType) {
            2 -> {
                // 俊鹏广播卸载
                val intent = Intent("com.mobilepower.terminal.message")
                intent.putExtra("type", 11)
                intent.putExtra("path", packageName)
                context.sendBroadcast(intent)
            }
            3 -> {
                // 印象service卸载
                YXServiceManager.unInStallApk(context, packageName)
            }
            else -> {
                // 默认卸载apk
                context.unInstallApk(packageName)
            }
        }
    }

    /**
     * 静默安装
     * */
    private fun installApk(context: Context) {
        //安装模式（0默认安装 2俊鹏广播安装 3印象service安装）
        log("UpdateAppReceiver-installApk-${updateConfig.installType}")
        when (updateConfig.installType) {
            0 -> {
                // 默认安装apk
                context.installApk(DownloadAppUtils.downloadUpdateApkFilePath)
            }
            1 -> {
                //静默安装
                AppUtil.instance.rootInstallApk(DownloadAppUtils.downloadUpdateApkFilePath)
            }
            2 -> {
                val intent = Intent("com.mobilepower.terminal.message")
                intent.putExtra("type", 3)
                intent.putExtra("path", DownloadAppUtils.downloadUpdateApkFilePath)
                log("UpdateAppReceiver-path===${DownloadAppUtils.downloadUpdateApkFilePath}")
                context.sendBroadcast(intent)
            }
            3 -> {
                YXServiceManager.inStallApk(context, DownloadAppUtils.downloadUpdateApkFilePath)
            }
            7 -> {
                var zcapi = zcapi()
                zcapi.getContext(context)
                zcapi.InstallApk(DownloadAppUtils.downloadUpdateApkFilePath,true)
            }
            else -> {
                // 默认安装apk
                context.installApk(DownloadAppUtils.downloadUpdateApkFilePath)
            }
        }
    }


    /**
     * 通知栏显示
     */
    private fun showNotification(
        context: Context,
        notifyId: Int,
        progress: Int,
        notificationChannel: String,
        nm: NotificationManager
    ) {

        val notificationName = "notification"

        // 适配 8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 通知渠道
            val channel = NotificationChannel(
                notificationChannel,
                notificationName,
                NotificationManager.IMPORTANCE_HIGH
            )
            channel.enableLights(false)
            // 是否在桌面icon右上角展示小红点
            channel.setShowBadge(false)
            // 是否在久按桌面图标时显示此渠道的通知
            channel.enableVibration(false)
            // 最后在notificationmanager中创建该通知渠道
            nm.createNotificationChannel(channel)
        }

        val builder = Notification.Builder(context)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(notificationChannel)
        }


        // 设置通知图标
        (updateConfig.notifyImgRes > 0).yes {
            builder.setSmallIcon(updateConfig.notifyImgRes)
            builder.setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    updateConfig.notifyImgRes
                )
            )
        }.no {
            builder.setSmallIcon(android.R.mipmap.sym_def_app_icon)
        }

        // 设置进度
        builder.setProgress(100, lastProgress, false)

        if (progress == -1000) {
            val intent = Intent(context.packageName + ACTION_RE_DOWNLOAD)
            intent.setPackage(context.packageName)
            val pendingIntent = PendingIntent.getBroadcast(
                context,
                REQUEST_CODE,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT
            )
            builder.setContentIntent(pendingIntent)
            // 通知栏标题
            builder.setContentTitle(uiConfig.downloadFailText)
        } else {
            // 通知栏标题
            builder.setContentTitle("${uiConfig.downloadingBtnText}$progress%")
        }


        // 设置只响一次
        builder.setOnlyAlertOnce(true)
        val notification = builder.build()
        nm.notify(notifyId, notification)
    }

    companion object {
        /**
         * 进度key
         */
        private const val KEY_OF_INTENT_PROGRESS = "KEY_OF_INTENT_PROGRESS"

        /**
         * ACTION_UPDATE
         */
        const val ACTION_UPDATE = "teprinciple.com.yundashi.updateapputils.update"

        /**
         * ACTION_RE_DOWNLOAD
         */
        const val ACTION_RE_DOWNLOAD = "action_re_download"


        const val REQUEST_CODE = 1001


        /**
         * 发送进度通知
         */
        fun send(context: Context, progress: Int) {
            val intent = Intent(context.packageName + ACTION_UPDATE)
            intent.putExtra(KEY_OF_INTENT_PROGRESS, progress)
            context.sendBroadcast(intent)
        }
    }
}